import classNames from "classnames";
import { useState } from "react";
import { ENTER_KEY, ESCAPE_KEY } from "@/Utils/constants";

const TodoItem: React.FC<ITodoItemProps> = ({
  todo,
  editing,
  onToggle,
  onDestroy,
  onEdit,
  onSave,
  onCancel,
}) => {
  const [editText, setEditText] = useState(todo.title);

  const handleEdit = () => {
    onEdit();
    setEditText(todo.title);
  };

  const handleSubmit = (event: React.FormEvent) => {
    let val = editText.trim();
    if (val) {
      onSave(val);
      setEditText(val);
    } else {
      onDestroy();
    }
  };

  const handleChange = (event: React.ChangeEvent) => {
    var target = event.target as any;
    if (editing) {
      setEditText(target.value);
    }
  };

  const handleKeyDown = (event: React.KeyboardEvent) => {
    if (event.which === ESCAPE_KEY) {
      setEditText(todo.title);
      onCancel(event);
    } else if (event.which === ENTER_KEY) {
      handleSubmit(event);
    }
  };

  return (
    <li
      className={classNames({
        completed: todo.completed,
        editing,
      })}
    >
      <div className="view">
        <input
          className="toggle"
          type="checkbox"
          checked={todo.completed}
          onChange={onToggle}
        />
        <label onDoubleClick={handleEdit}>{todo.title}</label>
        <button className="destroy" onClick={onDestroy} />
      </div>
      <input
        className="edit"
        value={editText}
        onBlur={(e) => handleSubmit(e)}
        onChange={(e) => handleChange(e)}
        onKeyDown={(e) => handleKeyDown(e)}
      />
    </li>
  );
};

export default TodoItem;
